<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridInstance, VxeGridListeners, VxeGridProps } from 'vxe-table'

import { MemberGetTagCatList, MemberTagDelete, MemberTagPage, MemberTagUpdateStatusById } from '@fl/api/anjutong'
import { ElCard } from 'element-plus'
import { reactive, ref } from 'vue'

import createTag from './create-tag.vue'

const getTagInformation = ref({})
const addDialogVisible = ref(false)
type RowVO = {
    lastUpdateTime: string
    name: string
    num: number
    status: string
    type: number

}

const xGrid = ref<VxeGridInstance<RowVO>>()

const searchForm = ref({
    mainCat: '',
    subCat: '',
    tagName: '',
})

const gridOptions = reactive<VxeGridProps<RowVO>>({
    border: true,
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'name', title: '标签名称' },
        { field: 'num', title: '标记数量' },
        { field: 'type', slots: { default: 'type' }, title: '标签类型' },
        { field: 'status', slots: { default: 'status' }, title: '标签状态' },
        { field: 'lastUpdateTime', title: '最后修改时间' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    pagerConfig: {
        currentPage: 1,
        enabled: true,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100, 200, 500],
        total: 0,
    },
    showOverflow: true,
})

const gridEvents: VxeGridListeners<RowVO> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        findList()
    },
}

const TagCatList = ref([])
const searchColumns: PlusColumn[] = [{
    colProps: {
        span: 8,
    },
    label: '一级分类',
    options: async () => {
        const data = await MemberGetTagCatList()
        TagCatList.value = data ?? []
        return data.map((item: any) => {
            return {
                label: item.label,
                value: item.label,
            }
        })
    },
    prop: 'mainCat',
    valueType: 'select',
}, {
    colProps: {
        span: 8,
    },

    label: '二级分类',
    options: computed(() => {
        if (searchForm.value.mainCat) {
            const params: any = TagCatList.value.find((item: any) => item.label === searchForm.value.mainCat)
            return params?.children.map((item: any) => {
                return {
                    label: item.label,
                    value: item.label,
                }
            }) ?? []
        }

        return []
    }),
    prop: 'subCat',
    valueType: 'select',
}, {
    colProps: {
        span: 8,
    },
    label: '标签名称',
    prop: 'tagName',
    valueType: 'copy',
}]
const dialogTitle = ref('')
async function findList() {
    gridOptions.loading = true
    const options = {
        mainCat: searchForm.value.mainCat,
        page: gridOptions.pagerConfig?.currentPage,
        size: gridOptions.pagerConfig?.pageSize,
        subCat: searchForm.value.subCat,
        tagName: searchForm.value.tagName,
    }
    const data: any = await MemberTagPage(options)
    console.log('🚀 ~ findList ~ data:', data)
    gridOptions.loading = false
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.total = data?.total ?? 0
    gridOptions.data = data?.records ?? []
}
findList()
function handleReset() {
    searchForm.value = {
        mainCat: '',
        subCat: '',
        tagName: '',
    }
    findList()
}
async function updateStatus(row: any) {
    gridOptions.loading = true
    await MemberTagUpdateStatusById(row.id)
    findList()
}
async function deleteRow(row: any) {
    gridOptions.loading = true
    console.log(row.id)
    await MemberTagDelete([row.id])
    ElMessage({
        message: '删除成功',
        type: 'success',
    })
    findList()
}
async function addTagInformation() {
    dialogTitle.value = '新建标签'
    addDialogVisible.value = true
    getTagInformation.value = {}
}
async function editMemberTag(row: any) {
    dialogTitle.value = '编辑标签'
    getTagInformation.value = row
    console.log(row, 'rowrowrowrow')
    addDialogVisible.value = true
}
function closeDialogTag() {
    addDialogVisible.value = false
    findList()
}
function search() {
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.currentPage = 1
    findList()
}
</script>

<template>
    <ElCard class="mb-20">
        <PlusForm v-model="searchForm"
                  :row-props="{ gutter: 20 }"
                  :columns="searchColumns"
        >
            <template #footer>
                <div class="ml-auto">
                    <el-button type="primary"
                               @click="search"
                    >
                        查询
                    </el-button>

                    <el-button @click="handleReset">
                        重置
                    </el-button>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard>
        <div class="my-10 flex justify-end">
            <el-button type="primary"
                       @click="addTagInformation"
            >
                新增
            </el-button>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
                  v-on="gridEvents"
        >
            <template #type="{ row }">
                {{ row?.type === 0 ? '自动标签' : "手动标签" }}
            </template>

            <template #status="{ row }">
                <vxe-switch :model-value="row.status === 1 ? true : false"
                            @change="updateStatus(row)"
                />
            </template>

            <template #operate="{ row }">
                <vxe-button content="编辑"
                            @click="editMemberTag(row)"
                />

                <vxe-button status="danger"
                            content="删除"
                            @click="deleteRow(row)"
                />
            </template>
        </vxe-grid>
    </ElCard>

    <el-dialog v-model="addDialogVisible"
               width="80%"
               :title="dialogTitle"
               :destroy-on-close="true"
    >
        <create-tag :get-tag-information="getTagInformation"
                    @close-dialog-tag="closeDialogTag"
        />
    </el-dialog>
</template>
